/**
 * 零星散户产地检疫申报单
 * @constructor
 */
function Investors() {
}

Investors.init = function () {
    getTown();
    loadCities();
    $('#tableList').bootstrapTable({
        url: '/investors/tableSearch',
        method: 'post',
        striped: true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
//search : "true",
        uniqueId: "id",
        pageList: [5, 10, 20, 50, 100],//可选择单页记录数
        pageSize: "10",
        pagination: true, // 是否分页
        sortable: true, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search: false,
        showColumns: true,
        showRefresh: true,
        showExport: true,
//得到查询的参数
        queryParams: function (params) {
//这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
//********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
//********
//获取查询的对象，往下加入
                declarant: $('#search_Declarant').val(), // 请求时向服务端传递的参数
            };
            return query_params;
        },
        columns: [
            {
//field: 'Number',//可不加
                title: '序号',//标题  可不加
                align: "center",
                width: 40,
                formatter: function (value, row, index) {
                    var pageSize = $('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber = $('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            {field: 'declarant', title: '申报人', align: 'center'},
            {field: 'idCard', title: '身份证号', align: 'center'},
            {field: 'dphone', title: '申报人联系电话', align: 'center'},
            {field: 'address', title: '养殖户所在乡镇', align: 'center'},
            {field: 'specificAddress', title: '具体地址', align: 'center'},
            {field: 'saleAddress', title: '销售去向', align: 'center'},
            {field: 'toSpecificAddress', title: '具体地点', align: 'center'},
            {field: 'buyer', title: '购买人', align: 'center'},
            {field: 'buyPhone', title: '购买人联系电话', align: 'center'},
            {field: 'animal', title: '动物种类', align: 'center'},
            {field: 'number', title: '数量', align: 'center'},
            {field: 'markStart', title: '耳标号从(猪)1350481、(禽)SM', align: 'center'},
            {field: 'markEnd', title: '至(猪)1350481、(禽)SM', align: 'center'},
            {field: 'purpose', title: '用途', align: 'center'},
            {field: 'nowPlace', title: '当前地点', align: 'center'},
            {
                field: 'photo', title: '动物产地检疫申报基本信息报告表照片', align: 'center', width: 200,
                formatter: function (value) {
                    return "<a href='"+value+"' target='_blank'>查看图片</a>";
                    // return "<img src=\"" + value + "\" class=\"img-responsive\">";
                }
            },
            {field: 'remark', title: '备注', align: 'center'},
            {field: 'inspectionPerson', title: '巡查人员签字', align: 'center'},
            {field: 'toInspectionPerson', title: '被巡查人员签字', align: 'center'},
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    optionHtml = optionHtml + "<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"edit\")' title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a>";
                    optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"delete\")'  title=\"删除\"><i class=\"fa fa-remove\"></i>删除</a>"
                    return optionHtml;
                }
            }
        ]
    });
}

function getTown() {
    console.log("进入多选框赋值方法")
    //给多选框赋值
    $.ajax({
        url: '/town/getTownByDistrictSession',
        type: "post",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            $("#text_address").empty();
            $.each(data, function (index, o) {
                $("#text_address").append("<label><input type=\"checkbox\" value=\"" + o.town__name + "\" name=\"checkbox\"/>" + o.town__name + "</label>")
            })
        }
    });
}

//查询方法****************************
function doSearch() {
// $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
    $("#tableList").bootstrapTable("refreshOptions", {pageNumber: 1});
}

//重置****************************
function doRest() {
    $("#search_Declarant").val("");
// $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
    $("#tableList").bootstrapTable("refreshOptions", {pageNumber: 1});
}

//增加方法****************************
var Action = "";
var id = 0;
var pxt = "/investors"; //控制器名称
function addRecord() {
    id = 0;
    Action = "add";
    $("#myform")[0].reset();

}

//增加/修改数据保存****************************
function saveRecord() {
    let address = "";
    $.each($("#text_address input[type=checkbox]:checked"), function () {
        address += $(this).val() + ","
    })
    address = address.substring(0, address.length - 1)
    if (!validateForm()) return false;


    let purpose = "";
    $.each($("#text_purpose input[type=checkbox]:checked"), function () {
        purpose += $(this).val() + ","
    })
    purpose = purpose.substring(0, purpose.length - 1)
//创建传递的参数
    var postdata = {
        id: id,
        action: Action,

        declarant: $("#text_declarant").val(),
        idCard: $("#text_idCard").val(),
        dphone: $("#text_dphone").val(),
        address: address,
        specificAddress: $("#text_specificAddress").val(),
        toProvince: $("#text_toProvince").val(),
        toCity: $("#text_toCity").val(),
        toDistrict: $("#text_toDistrict").val(),
        saleAddress: $("#text_toProvince").find("option:selected").text() + $("#text_toCity").find("option:selected").text() + $("#text_toDistrict").find("option:selected").text(),
        toSpecificAddress: $("#text_toSpecificAddress").val(),
        buyer: $("#text_buyer").val(),
        buyPhone: $("#text_buyPhone").val(),
        animal: $("#text_animal").val(),
        number: $("#text_number").val(),
        markStart: $("#text_markStart").val(),
        markEnd: $("#text_markEnd").val(),
        purpose: purpose,
        nowPlace: $("#text_nowPlace").val(),
        photo: photo,
        remark: $("#text_remark").val(),
        inspectionPerson: $("#text_inspectionPerson").val(),
        toInspectionPerson: $("#text_toInspectionPerson").val(),
    };
// console.log(JSON.stringify(postdata));
//发送异步请求到后台保存用户数据
    $.ajax({
        url: pxt + (Action == "add" ? "/save" : "/update"),
        type: "post",
        data: JSON.stringify(postdata),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}

//操作相关方法****************************
function actionRecord(data, type) {
    httpPhoto = data.photo;
    if (type == "edit") {
//修改
        id = data.id;
        Action = "edit";
        $("#myform")[0].reset();
        $("#save").removeAttr("disabled");
        WriteData(data)
        $('#myModalAdd').modal('show')
    } else {
//删除
        swal({
            title: "确认是否删除",
            text: "是否确认要删除该条记录？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
//点击删除之后此处进行传递后台
            $.ajax({
                type: "delete",
                url: pxt + "/deleteById/" + data.id,
                dataType: "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        doSearch();
                        swal("删除成功!", "请继续操作", "success");
                    } else {
                        swal("删除失败!", "请重试", "error");
                    }
                }
            });

        });
    }
}

//给控件赋值****************************
function WriteData(data) {
    $("#text_declarant").val(data.declarant);
    $("#text_idCard").val(data.idCard);
    $("#text_dphone").val(data.dphone);
    /**
     * 无法全部清空再赋值
     */
    $.each(data.address.split(","), function (index, object) {
        $.each($('#text_address input[type=checkbox]'), function () {
            if (object == $(this).val()) {
                $(this).attr("checked", true);
            }
        });
    })
    $("#text_specificAddress").val(data.specificAddress);
    $("#text_toProvince").val(data.toProvince);
    $("#text_toCity").val(data.toCity);
    $("#text_toDistrict").val(data.toDistrict);
    $("#text_toSpecificAddress").val(data.toSpecificAddress);
    $("#text_buyer").val(data.buyer);
    $("#text_buyPhone").val(data.buyPhone);
    $("#text_animal").val(data.animal);
    $("#text_number").val(data.number);
    $("#text_markStart").val(data.markStart);
    $("#text_markEnd").val(data.markEnd);
    $("#text_inspectionPerson").val(data.inspectionPerson);
    $("#text_toInspectionPerson").val(data.toInspectionPerson);
    /**
     * 无法全部清空再赋值
     */
    $.each(data.purpose.split(","), function (index, object) {
        $.each($('#text_purpose input[type=checkbox]'), function () {
            if (object == $(this).val()) {
                $(this).attr("checked", true);
            }
        });
    })
    $("#text_nowPlace").val(data.nowPlace);
    var strs = data.photo.split("/");
    var str = strs[strs.length - 1];
    photo = str;
    document.getElementById("showImage").style.display = "block";
    $("#showImage").attr("src", httpPhoto);
    $("#text_remark").val(data.remark);
}

//起运城市三级联动**************************
function loadCities() {
    $.ajax({
        url: "/city/tableSearch",
        type: "post",
        data: JSON.stringify({pageSize: 100}),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            initCitySelect(data.data);
            if (data.data[0]) {
                loadDistricts(data.data[0].city_id)
            }
        }
    });
}


function loadDistricts(city) {
    $.ajax({
        url: "/district/tableSearch",
        type: "post",
        data: JSON.stringify({city_id: $(city).val(), pageSize: 100}),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            initDistrictSelect(data.data);
        }
    });
}


function initCitySelect(data) {
    $('#text_toCity').empty();
    $.each(data, function (index, item) {
        $('#text_toCity').append("<option value='" + item.city_id + "'>" + item.city_name + "</option>");
    })
}

function initDistrictSelect(data) {
    $('#text_toDistrict').empty();
    $.each(data, function (index, item) {
        $('#text_toDistrict').append("<option value='" + item.district_id + "'>" + item.district_name + "</option>");
    })
}

var photo = "";//图片路径
var httpPhoto = ""    //图片完整路径
//上传****************************
function ImportShipmentStatusList() {
    console.log("进入图片上传方法")
    var upname = "text_photo";
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: pxt + '/uploadImages',
        secureuri: false,
        fileElementId: upname,
        dataType: 'json',
        success: function (data, status) {
            photo = data.url;
            //隐藏文件选择
            $("#uploadImages").css("display", "none");
            //图片回显
            $("#showImage").css("display", "");
            $("#showImage").attr("src", data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败", e);
        }
    });
}

//表单验证*****************************
function validateForm() {
//validate方法参数可选
    return $("#myform").validate({
        rules: {

            text_declarant: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_idCard: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_dphone: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_address: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toProvince: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toCity: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toDistrict: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toSpecificAddress: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_buyer: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_buyPhone: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_animal: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_number: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_markStart: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_markEnd: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_purpose: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_nowPlace: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_inspectionPerson: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toInspectionPerson: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
        },
//错误信息提示
        messages: {
            text_declarant: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_idCard: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_dphone: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_address: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toProvince: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toCity: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toDistrict: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toSpecificAddress: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_buyer: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_buyPhone: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_animal: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_number: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_markStart: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_markEnd: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_purpose: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_nowPlace: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_inspectionPerson: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_toInspectionPerson: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
        },
    }).form();

}
